package com.credit.mola.app.utils.dialog

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.core.net.toUri
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.credit.mola.app.R
import com.credit.mola.app.adapter.KefuContactAdapter
import com.credit.mola.app.app.App
import com.credit.mola.app.databinding.DialogKefuBinding
import com.credit.mola.app.pro.ProDialog
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.http.HttpHelper
import com.credit.mola.lib_baseadapter.SikadwaOnItemChildClickListener
import org.json.JSONObject


/**
 * Author : wwdeng
 * Date : 2023/8/1 15:44
 * <p>
 * 每天进步一点点
 * <p>
 * Desc : 客服dialog
 */
class KefuDialog: ProDialog {
    private lateinit var binding: DialogKefuBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""

    //联系方式列表
    var mContactAdapter: KefuContactAdapter? = null
    override fun initWindow() {
        val params = window?.attributes
        params?.width = App.app.getPhoneWidth() - DensityUtils.dp2px(32f)
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.dialog_scale_anim) //修改动画样式
        window?.setGravity(Gravity.TOP)
    }

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogKefuBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)
        params.setMargins(0, DensityUtils.dp2px(44f),0,0)
        binding.contactLayout.layoutParams = params

        initRvContact()
    }

    override fun initListener() {
        setOnClickListener(R.id.imgClose)
        setOnClickListener(R.id.btnKefuFeedback)
    }

    override fun initData() {
        if (Configs.getSPBoolean(Configs.SPKEY.SIKADWA_LOGIN)){
            binding.btnKefuFeedback.visibility = View.VISIBLE
        } else {
            binding.btnKefuFeedback.visibility = View.GONE
        }
    }

    override fun onViewClick(v: View?) {
        dismiss()
        if(mCallback != null){
            mCallback?.onClick(v)
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    /**
     * 初始化联系方式列表
     */
    private fun initRvContact() {
        binding.rvContact.setHasFixedSize(false)
        binding.rvContact.isNestedScrollingEnabled = false
        binding.rvContact.isFocusableInTouchMode = false //不需要焦点
        binding.rvContact.layoutManager = LinearLayoutManager(context)
        mContactAdapter = KefuContactAdapter(binding.rvContact)
        binding.rvContact.adapter = mContactAdapter
        binding.rvContact.itemAnimator = DefaultItemAnimator()
        mContactAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { parent, childView, position ->
            val item = mContactAdapter?.getItem(position)
            when (childView.id) {
                R.id.btnDial -> {//拨号
                    onCallAction(item)
                }
            }
        })
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject?){
        item?.let {
            val type = it.optString("type")
            HttpHelper.addEvent(EventType.CLICK.CLICK_USER_FEEDBACK_DIAL,type + "：" + it.optString("value"))
            val callIntent = Intent(Intent.ACTION_DIAL)
            callIntent.data = "tel:${it.optString("value")}".toUri()
            context.startActivity(callIntent)
        }
    }

    /**
     * 获取联系方式列表
     */
    fun loadKefuContactAction(){
        showCmCustomerWorkTime()
        val contactList = arrayListOf<JSONObject>()
        val customize = CustomConfigHelper.getCmConfigData()
        if (customize != null){
            val mobileStr = customize.optString("mobile","")
            if (mobileStr.isNotEmpty()){
                val mobileList = mobileStr.split(",")
                for (i in mobileList.indices){
                    val obj = JSONObject()
                    obj.put("type","MOBILE")
                    obj.put("value", mobileList[i])
                    contactList.add(obj)
                }
            }
            val emailStr = customize.optString("email","")
            if (emailStr.isNotEmpty()){
                val emailList = emailStr.split(",")
                for (i in emailList.indices){
                    val obj = JSONObject()
                    obj.put("type","EMAIL")
                    obj.put("value", emailList[i])
                    contactList.add(obj)
                }
            }
        }
        mContactAdapter?.data = contactList
    }

    /**
     * 设置客服工作时间
     */
    private fun showCmCustomerWorkTime(){
        //工作时间
        var workWeek = CustomConfigHelper.getCmCustomerWorkWeek()
        var workTime = CustomConfigHelper.getCmCustomerWorkTime()
        if (workWeek.isEmpty()){
            workWeek = context.getString(R.string.kefu_work_week)
        }
        if (workTime.isEmpty()){
            workTime = "9 am - 6 pm"
        }
        val showString = String.format(context.getString(R.string.kefu_work_time),workWeek,workTime)
        val spString = SpannableString(showString)
        val start = showString.indexOf(workTime)
        val end = start + workTime.length
        spString.setSpan(ForegroundColorSpan(context.getColor(R.color.FF4C8FFB)), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        // 创建一个StyleSpan对象，设置样式为Typeface.BOLD，即加粗
        val boldSpan = StyleSpan(Typeface.BOLD)
        spString.setSpan(boldSpan,start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.textWorkTime.text = spString
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addEvent(EventType.DIALOG.DIALOG_KEFU_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addEvent(EventType.DIALOG.DIALOG_KEFU_DISMISS,eventRemark)
    }
}